<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\CarOwner;
use App\Models\ScanLog;
use App\Models\Admin;
use App\Services\QrCodeService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\App;
use Carbon\Carbon;

class AdminController extends Controller
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->middleware('admin.auth');
    }
    
    /**
     * 仪表盘
     */
    public function dashboard()
    {
        // 获取统计数据
        $stats = [
            'users_count' => User::count(),
            'car_owners_count' => CarOwner::count(),
            'scans_count' => ScanLog::count(),
            'calls_count' => ScanLog::where('call_made', true)->count(),
        ];
        
        // 获取最近30天的扫码趋势
        $scansByDate = ScanLog::select(
            DB::raw('DATE(scan_time) as date'), 
            DB::raw('COUNT(*) as count')
        )
        ->where('scan_time', '>=', Carbon::now()->subDays(30))
        ->groupBy('date')
        ->orderBy('date')
        ->get();
        
        // 获取最近的扫码记录
        $recentScans = ScanLog::with(['scanner', 'carOwner.user'])
            ->orderBy('scan_time', 'desc')
            ->limit(10)
            ->get();
            
        return view('admin.dashboard', compact('stats', 'scansByDate', 'recentScans'));
    }
    
    /**
     * 用户管理
     */
    public function users(Request $request)
    {
        $query = User::query();
        
        // 搜索条件
        if ($request->filled('search')) {
            $query->where(function($q) use ($request) {
                $q->where('nickname', 'like', '%' . $request->search . '%')
                  ->orWhere('phone', 'like', '%' . $request->search . '%');
            });
        }
        
        // 日期筛选
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
        
        // 状态筛选
        if ($request->filled('status')) {
            $query->where('is_active', (bool)$request->status);
        }
        
        // 获取用户列表
        $users = $query->orderBy('id', 'desc')->paginate(15);
        
        return view('admin.users.index', compact('users'));
    }
    
    /**
     * 车主管理
     */
    public function carOwners(Request $request)
    {
        $query = CarOwner::with('user');
        
        // 搜索条件
        if ($request->filled('search')) {
            $query->where(function($q) use ($request) {
                $q->where('phone_number', 'like', '%' . $request->search . '%')
                  ->orWhereHas('user', function($u) use ($request) {
                      $u->where('nickname', 'like', '%' . $request->search . '%');
                  });
            });
        }
        
        // 日期筛选
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
        
        // 扫码次数筛选
        if ($request->filled('scan_count')) {
            $query->has('scanLogs', '>=', $request->scan_count);
        }
        
        // 附加统计数据
        $query->withCount(['scanLogs', 'scanLogs as calls_count' => function($q) {
            $q->where('call_made', true);
        }]);
        
        // 获取车主列表
        $carOwners = $query->orderBy('id', 'desc')->paginate(15);
        
        return view('admin.car_owners.index', compact('carOwners'));
    }
    
    /**
     * 扫码记录
     */
    public function scanLogs(Request $request)
    {
        $query = ScanLog::with(['scanner', 'carOwner.user']);
        
        // 扫码用户筛选
        if ($request->filled('scanner')) {
            $query->whereHas('scanner', function($q) use ($request) {
                $q->where('nickname', 'like', '%' . $request->scanner . '%');
            });
        }
        
        // 车主筛选
        if ($request->filled('car_owner')) {
            $query->whereHas('carOwner', function($q) use ($request) {
                $q->where('phone_number', 'like', '%' . $request->car_owner . '%')
                  ->orWhereHas('user', function($u) use ($request) {
                      $u->where('nickname', 'like', '%' . $request->car_owner . '%');
                  });
            });
        }
        
        // 日期筛选
        if ($request->filled('date_from')) {
            $query->whereDate('scan_time', '>=', $request->date_from);
        }
        
        if ($request->filled('date_to')) {
            $query->whereDate('scan_time', '<=', $request->date_to);
        }
        
        // 拨打状态筛选
        if ($request->filled('call_made')) {
            $query->where('call_made', (bool)$request->call_made);
        }
        
        // IP地址筛选
        if ($request->filled('ip_address')) {
            $query->where('ip_address', 'like', '%' . $request->ip_address . '%');
        }
        
        // 获取扫码记录
        $scanLogs = $query->orderBy('scan_time', 'desc')->paginate(20);
        
        // 扫码统计数据
        $scanStats = $this->getScanStats();
        
        // 电话拨打统计
        $callStats = [
            'called' => ScanLog::where('call_made', true)->count(),
            'not_called' => ScanLog::where('call_made', false)->count(),
        ];
        
        return view('admin.scan_logs.index', compact('scanLogs', 'scanStats', 'callStats'));
    }
    
    /**
     * 系统设置
     */
    public function settings()
    {
        // 系统设置
        $settings = [
            'app_name' => env('APP_NAME'),
            'app_url' => env('APP_URL'),
            'wechat_app_id' => env('WECHAT_APP_ID'),
            'wechat_app_secret' => env('WECHAT_APP_SECRET'),
        ];
        
        // 管理员列表
        $admins = Admin::all();
        
        // 系统信息
        $system_info = [
            'php_version' => phpversion(),
            'laravel_version' => App::version(),
            'database_type' => DB::connection()->getPdo()->getAttribute(\PDO::ATTR_DRIVER_NAME),
            'os' => php_uname('s') . ' ' . php_uname('r'),
            'web_server' => $_SERVER['SERVER_SOFTWARE'] ?? '未知',
            'users_count' => User::count(),
            'car_owners_count' => CarOwner::count(),
            'scans_count' => ScanLog::count(),
        ];
        
        return view('admin.settings.index', compact('settings', 'admins', 'system_info'));
    }
    
    /**
     * 更新系统设置
     */
    public function updateSettings(Request $request)
    {
        $request->validate([
            'app_name' => 'required|string|max:255',
            'app_url' => 'required|url',
            'wechat_app_id' => 'required|string|max:255',
            'wechat_app_secret' => 'required|string|max:255',
        ]);
        
        // 更新.env文件
        $this->updateEnvFile([
            'APP_NAME' => $request->app_name,
            'APP_URL' => $request->app_url,
            'WECHAT_APP_ID' => $request->wechat_app_id,
            'WECHAT_APP_SECRET' => $request->wechat_app_secret,
        ]);
        
        return redirect()->back()->with('success', '系统设置已更新');
    }
    
    /**
     * 更新.env文件
     */
    private function updateEnvFile($data)
    {
        $envFile = app()->environmentFilePath();
        $contentArray = file($envFile, FILE_IGNORE_NEW_LINES);
        
        foreach ($data as $key => $value) {
            // 如果值包含空格，用引号包裹
            if (strpos($value, ' ') !== false) {
                $value = '"' . $value . '"';
            }
            
            $found = false;
            foreach ($contentArray as $index => $line) {
                if (strpos($line, $key . '=') === 0) {
                    $contentArray[$index] = $key . '=' . $value;
                    $found = true;
                    break;
                }
            }
            
            if (!$found) {
                $contentArray[] = $key . '=' . $value;
            }
        }
        
        file_put_contents($envFile, implode("\n", $contentArray));
    }
    
    /**
     * 获取扫码统计数据
     */
    private function getScanStats()
    {
        $dates = [];
        $data = [];
        
        // 获取过去15天的日期
        for ($i = 14; $i >= 0; $i--) {
            $date = Carbon::now()->subDays($i)->format('Y-m-d');
            $dates[] = $date;
        }
        
        // 获取每日扫码数量
        $scanCounts = ScanLog::select(
            DB::raw('DATE(scan_time) as date'), 
            DB::raw('COUNT(*) as count')
        )
        ->where('scan_time', '>=', Carbon::now()->subDays(15))
        ->groupBy('date')
        ->pluck('count', 'date')
        ->toArray();
        
        // 填充数据数组
        foreach ($dates as $date) {
            $data[] = $scanCounts[$date] ?? 0;
        }
        
        return [
            'labels' => $dates,
            'data' => $data
        ];
    }
    
    /**
     * 导出扫码记录
     */
    public function exportScanLogs(Request $request)
    {
        $scanLogs = ScanLog::with(['scanner', 'carOwner'])
            ->orderBy('scan_time', 'desc')
            ->get();
            
        $filename = '扫码记录导出_' . date('YmdHis') . '.csv';
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];
        
        $callback = function() use ($scanLogs) {
            $file = fopen('php://output', 'w');
            // 添加CSV头部
            fputcsv($file, ['ID', '扫码用户', '车主信息', '扫码时间', '是否拨打电话', 'IP地址', '设备信息']);
            
            foreach ($scanLogs as $log) {
                fputcsv($file, [
                    $log->id,
                    $log->scanner ? $log->scanner->nickname : '未知用户',
                    $log->carOwner ? $log->carOwner->phone_number : '未知车主',
                    $log->scan_time,
                    $log->call_made ? '是' : '否',
                    $log->ip_address,
                    $log->device_info
                ]);
            }
            fclose($file);
        };
        
        return response()->stream($callback, 200, $headers);
    }
    
    /**
     * 导出用户数据
     */
    public function exportUsers(Request $request)
    {
        $users = User::with('carOwner')->get();
            
        $filename = '用户数据导出_' . date('YmdHis') . '.csv';
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];
        
        $callback = function() use ($users) {
            $file = fopen('php://output', 'w');
            // 添加CSV头部
            fputcsv($file, ['ID', '用户名', '头像', '手机号码', '注册时间', '是否创建挪车码', '挪车码被扫次数']);
            
            foreach ($users as $user) {
                // 获取该用户的扫码次数
                $scanCount = 0;
                if ($user->carOwner) {
                    $scanCount = ScanLog::where('car_owner_id', $user->carOwner->id)->count();
                }
                
                fputcsv($file, [
                    $user->id,
                    $user->nickname ?: '未设置',
                    $user->avatar_url ?: '未设置',
                    $user->carOwner ? $user->carOwner->phone_number : '未设置',
                    $user->created_at,
                    $user->carOwner ? '是' : '否',
                    $scanCount
                ]);
            }
            fclose($file);
        };
        
        return response()->stream($callback, 200, $headers);
    }
    
    /**
     * 导出车主数据
     */
    public function exportCarOwners(Request $request)
    {
        $carOwners = CarOwner::with('user')
            ->withCount(['scanLogs', 'scanLogs as calls_count' => function($q) {
                $q->where('call_made', true);
            }])
            ->get();
            
        $filename = '车主数据导出_' . date('YmdHis') . '.csv';
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];
        
        $callback = function() use ($carOwners) {
            $file = fopen('php://output', 'w');
            // 添加CSV头部
            fputcsv($file, ['ID', '用户名', '手机号码', '创建时间', '二维码路径', '扫码次数', '拨打电话次数']);
            
            foreach ($carOwners as $owner) {
                fputcsv($file, [
                    $owner->id,
                    $owner->user ? $owner->user->nickname : '未知用户',
                    $owner->phone_number,
                    $owner->created_at,
                    $owner->qr_code_path ?: '未生成',
                    $owner->scan_logs_count,
                    $owner->calls_count
                ]);
            }
            fclose($file);
        };
        
        return response()->stream($callback, 200, $headers);
    }
}
